package com.legolas.demo.web.controller;

import com.legolas.demo.domain.User;
import com.legolas.utils.JedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by haol on 2016/9/4.
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    JedisUtil jedisUtil;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String login() {
        return "/shiro/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String checkLogin(@RequestParam String username, @RequestParam String password, Model model) {
        logger.info("go into UserCon");
        //得到subject，其会自动绑定到当前线程
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("user_info", username);
            return "redirect:/user/list";
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
            model.addAttribute("account", username);
            model.addAttribute("error", e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            model.addAttribute("account", username);
            model.addAttribute("error", "系统发生错误");
        }
        return "/shiro/login";
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login/index";
    }
}
